#ifndef __std_buffer_h_
#define __std_buffer_h_

#include "config/type.h"
#include "sched/spinlock.h"

// 汇编空指令，等一个时钟周期
#define nop() asm volatile("nop")

// = 页大小, 4096 bytes
#define DEFAULT_BUFSIZE 4096
// 指针后移一位
#define move_next(x, capacity) (x = (x + 1) % capacity)
// 指针前移一位
#define move_prev(x, capacity) (x = (x - 1 + capacity) % capacity)

typedef struct { 
	uint cap; 		// 最大容量
	uint size;		// 已用容量
	uint head;		// 缓冲区头
	uint tail;		// 缓冲区尾
	uint peek;		// 访问指针
	// struct spinlock lock;			// 自旋锁
	// struct task_struct *producer;	// 生产者
	// struct task_struct *consumer;	// 消费者
	byte data[]; 	// 数据（柔性数组实现）
} buffer;

// (b->size == 0)
static inline int buffer_is_empty(buffer *b) {
	return (b->size == 0);
}

// (b->size == b->cap)
static inline int buffer_is_full(buffer *b) {
	return (b->size == b->cap);
}

// (b->peek == b->tail)
static inline int buffer_is_empty_peek(buffer *b) {
	return (b->peek == b->tail);
}

// (b->peek == b->head)
static inline int buffer_is_full_peek(buffer *b) {
	return (b->peek == b->head);
}

buffer *std_buffer_create();
void std_buffer_destroy(buffer *b);
void std_buffer_clear(buffer *b);
void std_buffer_put(buffer *b, const byte data);
void std_buffer_puts(buffer *b, const char *data);
byte std_buffer_pop_back(buffer *b);
byte std_buffer_pop_front(buffer *b);
int std_buffer_gets(buffer *b, char *data, int size);
byte std_buffer_peek(buffer *b);
void std_buffer_back(buffer *b);
char std_buffer_wait_char(buffer *b);
int std_buffer_wait_line(buffer *b, char *data, int size);

#endif